<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { vipPackages } from '../data/vipPackages';
import { VipLevel } from '../types/vip';
import type { VipInfo } from '../types/vip';
import {
  isVipActive,
  getVipLevel,
  formatVipLevel,
  getVipLevelColor,
  getUserWithVipInfo,
  saveVipInfo
} from '../utils/vipService';

const router = useRouter();
const selectedPackageId = ref('');
const isProcessing = ref(false);
const user = ref(getUserWithVipInfo());
const message = reactive({
  show: false,
  text: '',
  type: 'success' as 'success' | 'error' | 'info'
});

// 计算属性
const currentVipLevel = computed(() => getVipLevel(user.value?.vipInfo));
const isVip = computed(() => isVipActive(user.value?.vipInfo));
const vipLevelText = computed(() => formatVipLevel(currentVipLevel.value));
const vipLevelColor = computed(() => getVipLevelColor(currentVipLevel.value));

// 计算属性：VIP到期时间
const vipExpireDate = computed(() => {
  if (!user.value?.vipInfo?.expireDate) return '永久有效';
  return new Date(user.value.vipInfo.expireDate).toLocaleDateString();
});

// 显示消息提示
const showMessage = (text: string, type: 'success' | 'error' | 'info' = 'success') => {
  message.text = text;
  message.type = type;
  message.show = true;
  setTimeout(() => {
    message.show = false;
  }, 3000);
};

// 检查用户是否登录
const checkLogin = (): boolean => {
  if (!user.value) {
    showMessage('请先登录后再购买VIP服务', 'error');
    router.push('/auth?mode=login');
    return false;
  }
  return true;
};

// 处理VIP购买
const handlePurchase = async (packageId: string) => {
  if (!checkLogin()) return;
  
  isProcessing.value = true;
  selectedPackageId.value = packageId;
  
  try {
    // 模拟购买过程
    await new Promise(resolve => setTimeout(resolve, 1500));
    
    const selectedPackage = vipPackages.find(pkg => pkg.id === packageId);
    if (!selectedPackage) {
      throw new Error('套餐不存在');
    }
    
    // 计算到期日期
    const now = new Date();
    const expireDate = new Date(now.getTime() + selectedPackage.duration * 24 * 60 * 60 * 1000);
    
    // 创建VIP信息
    const vipInfo: VipInfo = {
      level: selectedPackage.level,
      expireDate: (expireDate ? expireDate.toISOString().split('T')[0] : null) as string | null,
        discountRate: selectedPackage.discountRate,
      isActive: true
    };
    
    // 保存VIP信息
    if (user.value) {
      saveVipInfo(user.value, vipInfo);
      user.value = getUserWithVipInfo();
      showMessage(`恭喜您成功购买${selectedPackage.name}！`, 'success');
    }
  } catch (error) {
    console.error('购买VIP失败:', error);
    showMessage('购买失败，请稍后重试', 'error');
  } finally {
    isProcessing.value = false;
  }
};

// 组件挂载时检查用户状态
onMounted(() => {
  // 定期更新用户信息
  const interval = setInterval(() => {
    user.value = getUserWithVipInfo();
  }, 5000);
  
  // 清理函数
  return () => clearInterval(interval);
});
</script>

<template>
  <div class="vip-page">
    <!-- 消息提示 -->
    <div 
      v-if="message.show" 
      class="message-toast" 
      :class="`message-${message.type}`"
    >
      {{ message.text }}
    </div>
    
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>VIP会员服务</h1>
      <p>尊享多重特权，购买电脑配件更优惠</p>
    </div>
    
    <!-- 用户VIP状态卡片 -->
    <div class="vip-status-card">
      <div class="vip-status-header">
        <h2>您的会员状态</h2>
        <div class="vip-badge" :style="{ backgroundColor: vipLevelColor }">
          {{ vipLevelText }}
        </div>
      </div>
      
      <div class="vip-status-content">
        <div v-if="isVip" class="vip-active-info">
          <p>会员有效期至：{{ vipExpireDate }}</p>
          <p>当前折扣：{{ (user?.vipInfo?.discountRate || 1) * 10 }}折</p>
        </div>
        <div v-else class="vip-inactive-info">
          <p>您当前不是VIP会员</p>
          <p>立即开通VIP，享受多重优惠和特权！</p>
        </div>
      </div>
    </div>
    
    <!-- VIP套餐选择 -->
    <div class="vip-packages-section">
      <h2>选择VIP套餐</h2>
      <div class="vip-packages-grid">
        <div 
          v-for="pkg in vipPackages" 
          :key="pkg.id"
          class="vip-package-card"
          :class="{ 
            'is-selected': selectedPackageId === pkg.id,
            'is-active': isVip && user?.vipInfo?.level === pkg.level
          }"
        >
          <div class="package-header">
            <h3>{{ pkg.name }}</h3>
            <div class="package-price">
              <span class="price">¥{{ pkg.price }}</span>
              <span class="duration">/{{ pkg.duration === 365 ? '年' : pkg.duration === 90 ? '季' : '月' }}</span>
            </div>
          </div>
          
          <div class="package-discount">
            购买配件享受{{ pkg.discountRate * 10 }}折优惠
          </div>
          
          <div class="package-description">
            {{ pkg.description }}
          </div>
          
          <div class="package-benefits">
            <div 
              v-for="(benefit, index) in pkg.benefits" 
              :key="index"
              class="benefit-item"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <polyline points="20 6 9 17 4 12"></polyline>
              </svg>
              <span>{{ benefit }}</span>
            </div>
          </div>
          
          <button 
            class="btn-purchase"
            @click="handlePurchase(pkg.id)"
            :disabled="isProcessing"
          >
            {{ isProcessing ? '处理中...' : (isVip && user?.vipInfo?.level === pkg.level ? '当前等级' : '立即购买') }}
          </button>
        </div>
      </div>
    </div>
    
    <!-- VIP特权说明 -->
    <div class="vip-benefits-section">
      <h2>VIP特权说明</h2>
      <div class="benefits-grid">
        <div class="benefit-card">
          <div class="benefit-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <line x1="12" y1="1" x2="12" y2="23"></line>
              <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>
            </svg>
          </div>
          <h3>专属折扣</h3>
          <p>根据VIP等级享受不同程度的配件和整机折扣，最高可达8折优惠。</p>
        </div>
        
        <div class="benefit-card">
          <div class="benefit-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <circle cx="12" cy="12" r="10"></circle>
              <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>
              <line x1="12" y1="17" x2="12.01" y2="17"></line>
            </svg>
          </div>
          <h3>优惠券搜索</h3>
          <p>白银及以上会员可搜索各大电商平台的配件优惠券，省钱更省心。</p>
        </div>
        
        <div class="benefit-card">
          <div class="benefit-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <rect x="2" y="7" width="20" height="14" rx="2" ry="2"></rect>
              <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"></path>
            </svg>
          </div>
          <h3>专属装机方案</h3>
          <p>定期获取专业定制的装机方案，满足不同需求和预算。</p>
        </div>
        
        <div class="benefit-card">
          <div class="benefit-icon">
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
              <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path>
            </svg>
          </div>
          <h3>优先客服支持</h3>
          <p>VIP会员享受优先客服响应，高级会员还可获得7x24小时专属客服。</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.vip-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 1.5rem;
}

/* 消息提示 */
.message-toast {
  position: fixed;
  top: 2rem;
  right: 2rem;
  padding: 1rem 1.5rem;
  border-radius: 4px;
  color: white;
  font-weight: bold;
  z-index: 1000;
  animation: slideIn 0.3s ease-out;
}

.message-success {
  background-color: #52c41a;
}

.message-error {
  background-color: #ff4d4f;
}

.message-info {
  background-color: #1890ff;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 页面标题 */
.page-header {
  text-align: center;
  margin-bottom: 3rem;
}

.page-header h1 {
  font-size: 2.5rem;
  color: #1a1a1a;
  margin-bottom: 0.5rem;
}

.page-header p {
  font-size: 1.2rem;
  color: #666;
  margin: 0;
}

/* VIP状态卡片 */
.vip-status-card {
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  color: white;
  border-radius: 12px;
  padding: 2rem;
  margin-bottom: 3rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.vip-status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.vip-status-header h2 {
  margin: 0;
  font-size: 1.8rem;
}

.vip-badge {
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-weight: bold;
  font-size: 0.9rem;
}

.vip-status-content p {
  margin: 0.5rem 0;
  font-size: 1.1rem;
}

/* VIP套餐选择 */
.vip-packages-section h2 {
  text-align: center;
  font-size: 2rem;
  margin-bottom: 2rem;
  color: #1a1a1a;
}

.vip-packages-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 2rem;
  margin-bottom: 3rem;
}

.vip-package-card {
  background-color: white;
  border: 2px solid #eaeaea;
  border-radius: 12px;
  padding: 2rem;
  transition: all 0.3s ease;
  position: relative;
}

.vip-package-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  border-color: #00ccff;
}

.vip-package-card.is-selected {
  border-color: #00ccff;
  box-shadow: 0 0 0 3px rgba(0, 204, 255, 0.1);
}

.vip-package-card.is-active {
  border-color: #52c41a;
  box-shadow: 0 0 0 3px rgba(82, 196, 26, 0.1);
}

.package-header h3 {
  margin: 0 0 1rem 0;
  font-size: 1.3rem;
  color: #1a1a1a;
}

.package-price {
  display: flex;
  align-items: baseline;
  margin-bottom: 1rem;
}

.package-price .price {
  font-size: 2rem;
  font-weight: bold;
  color: #00ccff;
  margin-right: 0.5rem;
}

.package-price .duration {
  color: #666;
  font-size: 0.9rem;
}

.package-discount {
  background-color: #f0f9ff;
  color: #00ccff;
  padding: 0.5rem;
  border-radius: 4px;
  font-weight: bold;
  margin-bottom: 1rem;
  text-align: center;
}

.package-description {
  color: #666;
  margin-bottom: 1.5rem;
  line-height: 1.6;
}

.package-benefits {
  margin-bottom: 2rem;
}

.benefit-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 0.75rem;
  color: #333;
}

.benefit-item svg {
  margin-right: 0.5rem;
  color: #00ccff;
  flex-shrink: 0;
  margin-top: 2px;
}

.btn-purchase {
  width: 100%;
  padding: 1rem;
  background-color: #00ccff;
  color: #1a1a1a;
  border: none;
  border-radius: 6px;
  font-size: 1.1rem;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.btn-purchase:hover:not(:disabled) {
  background-color: #00a3cc;
}

.btn-purchase:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* VIP特权说明 */
.vip-benefits-section h2 {
  text-align: center;
  font-size: 2rem;
  margin-bottom: 2rem;
  color: #1a1a1a;
}

.benefits-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 2rem;
}

.benefit-card {
  background-color: white;
  border-radius: 12px;
  padding: 2rem;
  text-align: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.benefit-card:hover {
  transform: translateY(-5px);
}

.benefit-icon {
  width: 60px;
  height: 60px;
  background-color: #f0f9ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 1.5rem auto;
  color: #00ccff;
}

.benefit-card h3 {
  margin: 0 0 1rem 0;
  font-size: 1.3rem;
  color: #1a1a1a;
}

.benefit-card p {
  color: #666;
  margin: 0;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .vip-status-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .page-header h1 {
    font-size: 2rem;
  }
  
  .vip-packages-grid,
  .benefits-grid {
    grid-template-columns: 1fr;
  }
}
</style>